package org.dromara.common.mqtt.domain;

import lombok.extern.slf4j.Slf4j;
import org.dromara.common.mqtt.config.properties.MqttProperties;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description : MQTT接受服务的客户端
 * @Author : lsyong
 * @Date : 2023/8/1 16:26
 */
@Slf4j
@Component
public class CustomMqttClient {

    public static MqttClient client;

    @Autowired
    private MqttProperties mqttProperties;

    public static void setClient(MqttClient client) {
        CustomMqttClient.client = client;
    }

    /**
     * 关闭连接
     */
    public static void disconnect(MqttClient mqttClient) {
        try {
            if (mqttClient != null)
                mqttClient.disconnect();
        } catch (MqttException e) {
            log.error("MqttSendClient disconnect error", e);
        }
    }

    /**
     * 释放资源
     */
    public static void close(MqttClient mqttClient) {
        try {
            if (mqttClient != null)
                mqttClient.close();
        } catch (MqttException e) {
            log.error("MqttSendClient close error,", e);
        }
    }

    /**
     * 重新连接
     */
    public void reconnection() {
        try {
            client.connect();
        } catch (MqttException e) {
            log.error("MqttAcceptClient reconnection error", e);
        }
    }

    /**
     * 订阅某个主题
     *
     * @param topic 主题
     * @param qos   连接方式
     */
    public void subscribe(String topic, int qos) {
        log.info("========================【开始订阅主题:{}】========================", topic);
        try {
            client.subscribe(topic, qos);
        } catch (MqttException e) {
            log.error("MqttAcceptClient subscribe error", e);
        }
    }

    /**
     * 取消订阅某个主题
     */
    public void unsubscribe(String topic) {
        log.info("========================【取消订阅主题:{}】========================", topic);
        try {
            client.unsubscribe(topic);
        } catch (MqttException e) {
            log.error("MqttAcceptClient unsubscribe error", e);
        }
    }

    /**
     * 发布消息
     *
     * @param retained 是否保留
     * @param topic    主题，格式： server:${env}:report:${topic}
     * @param content  消息内容
     */
    public void publish(boolean retained, String topic, String content) {
        MqttMessage message = new MqttMessage();
        message.setQos(mqttProperties.getQos());
        message.setRetained(retained);
        message.setPayload(content.getBytes());
        try {
            client.publish(topic, message);
        } catch (MqttException e) {
            log.error("MqttSendClient publish error", e);
        }
    }
}